package com.wyt.cloud.utils;


import java.beans.Introspector;
import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Method;
import java.util.regex.Pattern;

public class Reflections {

    private static final Pattern GET_PATTERN = Pattern.compile("^get[A-Z].*");
    private static final Pattern IS_PATTERN = Pattern.compile("^is[A-Z].*");


    private Reflections() {
    }


    public static <T, R> String fnToFieldName(Fn<T, R> fn) {
        String getter = fnToMethodName(fn);
        if (GET_PATTERN.matcher(getter).matches()) {
            getter = getter.substring(3);
        } else if (IS_PATTERN.matcher(getter).matches()) {
            getter = getter.substring(2);
        }
        return Introspector.decapitalize(getter);
    }


    public static <R, T> String fnToMethodName(Fn<T, R> fn) {
        try {
            Method method = fn.getClass().getDeclaredMethod("writeReplace");
            method.setAccessible(Boolean.TRUE);
            SerializedLambda serializedLambda = (SerializedLambda) method.invoke(fn);
            return serializedLambda.getImplMethodName();
        } catch (ReflectiveOperationException e) {
            throw new RuntimeException(e);
        }
    }


}
